package com.ds.sign.tool;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XmlUtils {

	/**
	 * 转化XML
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> parseRequestToMap(
			HttpServletRequest request) {
		try {
			return XmlUtils.parseInputStramToMap(request.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private static Map<String, Object> parseInputStramToMap(
			InputStream inputStream) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Reader reader = new InputStreamReader(inputStream, "UTF-8");
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(reader);
			Element root = document.getRootElement();
			List<Element> elementList = root.elements();
			for (Element e : elementList) {
				if (e.elements().size() > 0) {
					Map<String, Object> subMap = new HashMap<>();
					for (Element item : (List<Element>)e.elements()) {
						if (item.elements().size() > 0) {
							Map<String, Object> childMap = new HashMap<>();
							subMap.put(item.getName(), childMap);
							for (Element child : (List<Element>)item.elements()) {
								childMap.put(child.getName(), child.getText());
							}
						} else {
							subMap.put(item.getName(), item.getText());
						}
					}
					map.put(e.getName(), subMap);
				} else {
					map.put(e.getName(), e.getText());
				}
			}
			// 释放资源
			inputStream.close();
			inputStream = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * string格式的XML转map
	 * 
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> parseStringXmlToMap(String xml) {
		InputStream is = new ByteArrayInputStream(xml.getBytes());
		return XmlUtils.parseInputStramToMap(is);
	}

	/**
	 * @Description：将请求参数转换为xml格式的string
	 * @param parameters
	 *            请求参数
	 * @return
	 */
	public static String getRequestXml(SortedMap<Object, Object> parameters) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>");
		Set<Map.Entry<Object, Object>> es = parameters.entrySet();
		Iterator<Map.Entry<Object, Object>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<Object, Object> entry = it
					.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k)
					|| "sign".equalsIgnoreCase(k)) {
				sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
			} else {
				sb.append("<" + k + ">" + v + "</" + k + ">");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}
}
